<template>
  <div style="position:relative;height: 100vh;overflow: auto;" ref="wrapper">
    <div class="user-action">
      <div @click="goBack">
        <i class="el-icon-back" style="font-weight: bold;font-size:16px;color:#969696;"></i>
      </div>
      <div v-if="article.collectionStatus === '0'" @click="likeCollect('1','1')"><img src="../../../assets/img/collect1.png" alt=""></div>
      <div style="background: #ec7259;" v-if="article.collectionStatus === '1'" @click="likeCollect('1','0')"><img src="../../../assets/img/collect2.png" alt=""></div>
      <div v-if="article.likeStatus === '0'" @click="likeCollect('0','1')"><img src="../../../assets/img/zan1.png" alt=""></div>
      <div style="background: #ec7259;" v-if="article.likeStatus === '1'" @click="likeCollect('0','0')"><img src="../../../assets/img/zan2.png" alt=""></div>
      <div @click="share(article.id, article.articleTitle)"><img src="../../../assets/img/share2.png" alt=""></div>
      <div @click="scrollTop"><img src="../../../assets/img/top.png" alt=""></div>
    </div>
    <div class="wrapper">
      <p class="title">{{article.articleTitle}}</p>
      <p class="desc">
        <span>作者：{{article.articleMasterName}}</span>
        <span>发布时间：{{article.articleCreatetime}}</span>
        <span>更新时间：{{article.articleModifytime}}</span>
      </p>
      <div class="article w-e-text" v-html="article.articleContent"></div>
      <div class="file-list" v-if="article.articleAttachment.length > 0">
        <div class="file-left">
          附件：
        </div>
        <div class="file-right">
          <div v-for="file in article.articleAttachment" :key="file.uid">
            <a @click="downloadFile(file.url, file.name)" href="#">{{file.name}}</a>
          </div>
        </div>
      </div>
      <div class="my-comment">
        <p>我要留言</p>
        <div class="my-comment-content">
          <div class="avatar"><img :src="userInfo.avatar" alt=""></div>
          <at-ta style="width: 100%;" :members="members" name-key="name">
            <el-input style="width: 100%;" rows="4" v-model="myComment" type="textarea"></el-input>
            <div style="text-align:right;margin-top: 10px;">
              <input style="display:none;" type="file" @change="uploadFile($event, myCommentAttachment)" multiple="multiple">
              <span class="addfilebtn" @click="openUpload($event)"><i class="el-icon-paperclip"></i>添加附件</span>
              <el-button type="primary" style="padding: 6px 14px;" @click="reply(false)">发布</el-button>
            </div>
            <div class="fileitem" v-for="(file, idx) in myCommentAttachment" :key="idx">
              <span style="cursor: pointer;color: #45c2b5;" @click="downloadFile(file.url, file.name)">
                {{file.name}}
              </span>
              <span class="uploadtip" style="cursor:pointer;" v-if="file.url" @click="delFile(idx, myCommentAttachment)"><i class="el-icon-delete"></i></span>
              <span class="uploadtip" style="color: red;cursor:none;" v-if="!file.url">上传中<i class="el-icon-loading"></i></span>
            </div>
          </at-ta>
        </div>
      </div>
      <div class="comments">
        <p>用户评论</p>
        <div class="comments-list">
          <div v-for="comment in commentsList" :key="comment.id" class="comment-item">
            <div class="avatar"><img :src="comment.avatar" alt=""></div>
            <div class="comment-content">
              <div class="content-top">
                <p class="user-name">{{comment.reviewMasterName}}</p>
                <p class="content" style="white-space: pre-line;">{{comment.reviewContent}}</p>
                <div style="padding-left: 0;margin-top: 10px;border-top: 1px dashed #ECECEC;padding-top: 10px;" class="file-list" v-if="comment.reviewAttachment.length > 0">
                  <div class="file-left">
                    附件：
                  </div>
                  <div class="file-right">
                    <div v-for="file in comment.reviewAttachment" :key="file.uid">
                      <a @click="downloadFile(file.url, file.name)" href="#">{{file.name}}</a>
                    </div>
                  </div>
                </div>
                <p class="comment-action">
                  <span>{{comment.reviewCreatetime}}</span>
                  <span class="btns">
                    <span v-if="comment.reviewMasterId === userInfo.dingId" @click="editReply(comment)"><i class="el-icon-edit"></i>编辑</span>
                    <span v-if="comment.reviewMasterId !== userInfo.dingId" @click="openReply(comment)"><img style="width:12px;vertical-align:baseline;" src="../../../assets/img/reply.png">回复</span>
                    <span v-if="comment.reviewMasterId === userInfo.dingId || isMg" @click="delReply(false,comment)"><i class="el-icon-delete"></i>删除</span>
                  </span>
                </p>
                <div class="first-reply" v-if="comment.showReply">
                  <at-ta style="width: 100%;" :members="members" name-key="name">
                    <el-input style="width: 100%;" rows="4" v-model="comment.replyContent" type="textarea"></el-input>
                    <div style="text-align:right;margin-top: 10px;">
                      <input style="display:none;" type="file" @change="uploadFile($event, comment.attachment)" multiple="multiple">
                      <span class="addfilebtn" @click="openUpload($event)"><i class="el-icon-paperclip"></i>添加附件</span>
                      <el-button type="primary" style="padding: 6px 14px;" @click="reply(comment)">发布</el-button>
                    </div>
                    <div class="fileitem" v-for="(file, idx) in comment.attachment" :key="idx">
                      <span style="cursor: pointer;color: #45c2b5;" @click="downloadFile(file.url, file.name)">
                        {{file.name}}
                      </span>
                      <span class="uploadtip" style="cursor:pointer;" v-if="file.url" @click="delFile(idx, comment.attachment)"><i class="el-icon-delete"></i></span>
                      <span class="uploadtip" style="color: red;cursor:none;" v-if="!file.url">上传中<i class="el-icon-loading"></i></span>
                    </div>
                  </at-ta>
                </div>
                <div class="feedback-list" v-if="comment.childComment && comment.childComment.length > 0">
                  <div class="feedback-item" v-for="childComment in comment.childComment" :key="childComment.id">
                    <div class="feedback-content" style="position:relative;">
                      <div>
                        <span class="name-class">{{childComment.reviewMasterName}}：</span><span v-if="childComment.reviewNoticeUser">回复<span class="name-class">&nbsp;{{childComment.reviewNoticeUser}}：</span></span>
                        <span style="white-space: pre-line;">{{childComment.reviewContent}}</span>
                      </div>
                      <div style="padding-left: 0;margin-top: 10px;border-top: 1px dashed #ECECEC;padding-top: 10px;" class="file-list" v-if="childComment.reviewAttachment.length > 0">
                        <div class="file-left">
                          附件：
                        </div>
                        <div class="file-right">
                          <div style="margin-bottom: 0;" v-for="file in childComment.reviewAttachment" :key="file.uid">
                            <a @click="downloadFile(file.url, file.name)" href="#">{{file.name}}</a>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div class="feedback-action">
                      <span>{{childComment.reviewCreatetime}}</span>
                      <span class="btns">
                        <span v-if="childComment.reviewMasterId !== userInfo.dingId"  @click="openReply(childComment)"><img style="width:12px;vertical-align:baseline;" src="../../../assets/img/reply.png">回复</span>
                        <span v-if="childComment.reviewMasterId === userInfo.dingId" @click="editReply(childComment)"><i class="el-icon-edit"></i>编辑</span>
                        <span v-if="childComment.reviewMasterId === userInfo.dingId || isMg" @click="delReply(true,childComment,comment)"><i class="el-icon-delete"></i>删除</span>
                      </span>
                    </div>
                    <div class="reply" v-if="childComment.showReply">
                      <at-ta style="width: 100%;" :members="members" name-key="name">
                        <el-input style="width: 100%;" rows="4" v-model="childComment.replyContent" type="textarea"></el-input>
                        <div style="text-align:right;margin-top: 10px;">
                          <input style="display:none;" type="file" @change="uploadFile($event, childComment.attachment)" multiple="multiple">
                          <span class="addfilebtn" @click="openUpload($event)"><i class="el-icon-paperclip"></i>添加附件</span>
                          <el-button type="primary" style="padding: 6px 14px;" @click="reply(childComment, comment.id)">发布</el-button>
                        </div>
                        <div class="fileitem" v-for="(file, idx) in childComment.attachment" :key="idx">
                          <span style="cursor: pointer;color: #45c2b5;" @click="downloadFile(file.url, file.name)">
                            {{file.name}}
                          </span>
                          <span class="uploadtip" style="cursor:pointer;" v-if="file.url" @click="delFile(idx, childComment.attachment)"><i class="el-icon-delete"></i></span>
                          <span class="uploadtip" style="color: red;cursor:none;" v-if="!file.url">上传中<i class="el-icon-loading"></i></span>
                        </div>
                      </at-ta>
                    </div>
                  </div>
                </div>
              </div>
              <div style="height: 46px;line-height: 46px;text-align:center;background:#f5f5f5;" v-if="comment.childComment && comment.childComment.length === 3 && !comment.showAllChild" class=""><span style="cursor:pointer;" @click="getAllChildComment(comment)">查看全部回复></span></div>
            </div>
          </div>
        </div>
        <div style="height: 46px;line-height: 46px;text-align:center;background:#f5f5f5;" v-if="!isShowAllCommment && commentsList.length === 3" class=""><span style="cursor:pointer;" @click="openAllComment">查看全部评论></span></div>
      </div>
    </div>
  </div>
</template>

<script>
import sinaEmotions from '@/assets/emotion/sina'
import dingMixin from  '@/mixins/ding'
import formUtil from '@/utils/formUtil'
import AtTa from 'vue-at/dist/vue-at-textarea'

export default {
  name: 'Article',
  data () {
    return {
      myComment:'',
      myCommentAttachment: [],
      members: [],
      showReply: false,
      article: {
        sectionId: '',
        articleTitle: '',
        articleMasterId: '',
        articleMasterName: '',
        articleInfo: '',
        articleContent: '',
        articleStatus: '',
        articleAttachment: [],
        articleCount: '',
        articleLikecount: '',
        articleCreatetime: '',
        articleModifytime: '',
        collectionStatus: '0',
        likeStatus: '0',
        id: '',
      },
      commentsList: [],
      editorContainer: {},
      isShowAllCommment:false
    }
  },
  props: ['articleId', 'isMg'],
  components:{
      AtTa
  },
  mixins: [dingMixin],
  methods: {
    share(id, title) {
      this.complexPicker(1).then(async (data) => {
        if(!await this.$httpN.postB('community/article/share', {
          usernames: '@' + data[0].name,
          content: title,
          url: id
        })) return;
        formUtil.submitSuccess('分享成功');
      })
    },
    goBack() {
      this.$router.go(-1)
    },
    scrollTop() {
      this.$refs.wrapper.scrollTop = 0;
    },
    openUpload(el){
      el.target.parentNode.firstChild.click()
    },
    async uploadFile(e, target) {
      var files = e.target.files;
      var $this = this;
      Object.keys(files).forEach(function(key){
        var file = files[key];
        if(file.size / 1024 / 1024 > 20) return $this.mobileAlert('上传单个文件大小不能超过20MB!请压缩文件')
        var formData = new FormData();
        formData.append("file", file);
        formData.append("name", 'file');
        let newfile = {
          name: file.name,
          url: '',
        }
        target.push(newfile)
        $this.$httpN.upload('fileUpload', formData).then(res => {
          if(res.data.code === 0) {
            newfile.url = res.data.url;;
          }else if(res.data.code === 500) {
            target.pop();
          }
        })
      })
      e.target.value = '';
    },
    delFile(idx,target){
      target.splice(idx, 1)
    },
    async likeCollect(type, status){
      if(!await this.$httpN.postB('community/likecollection/like', {
        userId: this.userInfo.dingId,
        contextId: this.article.id,
        contextTitle: this.article.articleTitle,
        dataType: type,
        status: status
      })) return
      formUtil.submitSuccess((status === '0'? '取消': '') + (type === '0'? '点赞': '收藏') + '成功');

      if(type === '0') {
        this.article.likeStatus = status;
      }else if(type === '1') {
        this.article.collectionStatus = status;
      }
    },
    openReply(comment) {
      comment.showReply = !comment.showReply;
      comment.replyContent = '';
    },
    editReply(comment) {
      comment.showReply = !comment.showReply;
      comment.replyContent = comment.reviewContent;
      comment.attachment = formUtil.deepCopy(comment.reviewAttachment);
    },
    delReply(isChild,comment,parentComment) {
      formUtil.submitConfirm('此操作将永久删除评论及评论下的回复, 是否继续?', async ()=> {
        if(!await this.$httpN.postB('community/review/delete', {ids: comment.id}, false)) return;
        formUtil.submitSuccess('删除成功');
        if(!isChild) {
          this.getComment();
        }else {
          this.getAllChildComment(parentComment);
        }
      })
    },
    downloadFile: function (url, fileName) {//跨域文件路径、下载到本地的文件名
      if(/\.(bmp|gif|jpg|pic|png|tif|jpeg)$/.test(url)) return this.dingPreviewPic(url);
      var x = new XMLHttpRequest();
      x.open("GET", url, true);
      x.responseType = 'blob';
      x.onload=function(e) {
        var url = window.URL.createObjectURL(x.response)
        var a = document.createElement('a');
        a.href = url
        a.download = fileName;
        a.click()
      }
      x.send();
    },
    async openAllComment() {
      this.isShowAllCommment = true;
      let result = await this.$httpN.postB('community/review/list', {page: 2, dataType:0, articleId: this.article.id})
      result.forEach(element => {
        element.showReply = false;
        element.childComment = [];
        element.showAllChild = false;
        element.replyContent = '';
        element.attachment = element.reviewAttachment? JSON.parse(element.reviewAttachment): [];
        element.reviewAttachment = element.reviewAttachment? JSON.parse(element.reviewAttachment): [];
      });
      this.commentsList = result;
      let commentsId = result.map(item => item.id)
      this.getSomeChildComment(commentsId.join(','))
    },
    async getComment(comment, parentId) {
      if(!comment) {
        this.isShowAllCommment = false;
        this.getParentComment();
      }else {
        this.getAllChildComment(comment, parentId);
      }
    },
    async getAllChildComment(comment, parentId) {
      comment.showAllChild = true;
      let childComment = await this.$httpN.postB('community/review/list', {page: 2,dataType: 1,articleId: this.article.id, replyReviewIds: parentId? parentId: comment.id});
      childComment[parentId? parentId: comment.id].forEach(element => {
        element.showReply = false;
        element.replyContent = '';
        element.attachment = element.reviewAttachment? JSON.parse(element.reviewAttachment): [];
        element.reviewAttachment = element.reviewAttachment? JSON.parse(element.reviewAttachment): [];
      });
      this.commentsList.forEach((item) => {
        if(item.id === parentId || item.id === comment.id){
          item.childComment = childComment[parentId? parentId: comment.id];
        }
      })
    },
    async getSomeChildComment(ids) {
      let childComment = await this.$httpN.postB('community/review/list', {page: 1,dataType: 1,articleId: this.article.id, replyReviewIds: ids})
      for(let parentId in childComment) {
        childComment[parentId].forEach(element => {
          element.showReply = false;
          element.replyContent = '';
          element.attachment = element.reviewAttachment? JSON.parse(element.reviewAttachment): [];
          element.reviewAttachment = element.reviewAttachment? JSON.parse(element.reviewAttachment): [];
        });
        this.commentsList.forEach((parent) => {
          if(parent.id === parentId) parent.childComment.push(...childComment[parentId])
        })
      }
    },
    async getParentComment() {
      let result = await this.$httpN.postB('community/review/list', {page: 1,dataType: 0,articleId: this.article.id})
      result.forEach(element => {
        element.showReply = false;
        element.childComment = [];
        element.showAllChild = false;
        element.replyContent = '';
        element.attachment = element.reviewAttachment? JSON.parse(element.reviewAttachment): [];
        element.reviewAttachment = element.reviewAttachment? JSON.parse(element.reviewAttachment): [];
      });
      this.commentsList = result;
      let commentsId = this.commentsList.map(item => item.id);
      this.getSomeChildComment(commentsId.join(','))
    },
    async reply(comment, parentId) {
      let content = comment? comment.replyContent: this.myComment;
      let attachment = comment? comment.attachment: this.myCommentAttachment;
      if(!content) return this.$message.error('请输入回复内容')
      if(!comment || this.userInfo.dingId !== comment.reviewMasterId) {
        if(! await this.$httpN.postB('community/review/save', {
          articleId: this.article.id,
          replyReviewId: parentId ? parentId : comment? comment.id: '',
          reviewContent: content,
          reviewAttachment: attachment,
          reviewMasterId: this.userInfo.dingId,
          reviewMasterName: this.userInfo.realName,
          reviewNoticeUser: parentId? comment.reviewMasterName: '',
          content: this.article.articleTitle,
          url: this.article.id
        })) return 
        formUtil.submitSuccess('回复成功');
        if(comment) {
          comment.replyContent = '';
          comment.showReply = false;
          comment.attachment = [];
        }else {
          this.myComment = '';
          this.myCommentAttachment = [];
        }
        this.getComment(comment, parentId);
      }else {
        if(! await this.$httpN.postB('community/review/update', {
          id: comment.id,
          reviewContent: content,
          reviewAttachment: attachment
        })) return 
        formUtil.submitSuccess('编辑成功');
        if(comment && parentId ){
          this.getComment(comment, parentId);
        }else{
          this.getComment();
        }
      }
    },
    previewImg(img) {
      this.dingPreviewPic(img.target.src)
    }
  },
  async mounted() {
    let article = await this.$httpN.get('community/article/info/' + this.$route.params.articleId);
    if(article.articleStatus !== '1') {
      return formUtil.submitConfirm('文章已被删除，请返回', async ()=> {
        this.goBack();
      })
    }
    article.articleAttachment = JSON.parse(article.articleAttachment);
    this.article = article;
    this.getComment();
    this.loadMembers().then(data=>this.members = data);

    this.$nextTick(() => {
      let imgArr = document.querySelectorAll('[data-role]')
      imgArr.forEach((img) => {
        img.addEventListener('click', this.previewImg);
      })
    })
  }
}
</script>

<style lang="scss" scoped>
  .user-action{
    position: fixed;
    top: 300px;
    right: 100px;
    z-index: 99;
    div{
      width: 48px;
      height: 48px;
      line-height: 48px;
      margin-bottom: 20px;
      border-radius: 50%;
      background: white;
      cursor: pointer;
      text-align: center;
      box-shadow: 0 2px 10px rgba(0,0,0,.2);
      img{
        width: 16px;
        height: 16px;
      }
    }
  }
  .wrapper{
    max-width: 980px;
    margin:0 auto;
    position: relative;
    overflow-y: auto;
    .title{
      font-size: 26px;
      font-weight: bold;
      text-align: center;
    }
    .desc{
      text-align: center;
      color: #999;
      font-size: 12px;
      span + span{
        &::before{
          content: '|';
          margin:0 5px;
        }
      }
    }
    .article{
      line-height:30px;
    }
    .file-list{
      margin-top: 20px;
      padding: 0 10px;
      display: flex;
      .file-left{
        width: 50px;
      }
      .file-right{
        flex: 1;
        >div{
          margin-bottom: 5px;
        }
      }
    }
  }
  .comments{
    margin-top:50px;
    &>p{
      margin:0;
      color:#3753A2;
      font-size: 18px;
      line-height:47px;
      font-weight: bold;;
    }
    .comments-list{
      border: 1px solid #e8e8e8;
      border-top: 2px solid #3753a2;
      padding: 0 30px;
      p{
        margin: 0;
      }
      .comment-item{
        padding: 12px 0 10px;
        display: flex;
        border-bottom: 1px solid #e8e8e8;
        .avatar{
          width: 76px;
          img{
            width: 46px;
            height: 46px;
            border-radius: 100%;
            display:block;
          }
        }
        .comment-content{
          flex: 1;
          .user-name{
            color:#3753a2;
            font-size: 14px;
            font-weight: bold;
            line-height:24px;
          }
          .content{
            font-size: 14px;
            line-height:24px;
            word-break: break-all;
          }
          .comment-action{
            line-height:24px;
            position: relative;
            font-size: 14px;
            text-align: left;
            color: #999;
            .btns{
              float: right;
              span{
                cursor: pointer;
                margin-left:15px;
              }
            }
          }
          .feedback-list{
            margin-top: 5px;
            background: #f5f5f5;
            .feedback-item{
              padding: 12px 20px 10px;
              border-bottom: 1px solid #e8e8e8;
              &:last-child{
                border: none;
              }
              .feedback-content{
                font-size: 14px;
                line-height:24px;
                span.name-class{
                  color:#3753a2;
                  font-weight: bold;
                }
              }
              .feedback-action{
                line-height:24px;
                position: relative;
                font-size: 14px;
                text-align: left;
                color: #999;
                .btns{
                  float: right;
                  span{
                    cursor: pointer;
                    margin-left:15px;
                  }
                }
              }
            }
          }
        }
      }

    }
  }
  .my-comment{
    margin-top:120px;
    &>p{
      margin:0;
      color:#3753A2;
      font-size: 18px;
      line-height:47px;
      font-weight: bold;;
    }
    .my-comment-content{
      border: 1px solid #e8e8e8;
      border-top: 2px solid #3753a2;
      padding: 20px 30px;
      display: flex;
      .avatar{
        width: 76px;
        img{
          width: 46px;
          height: 46px;
          border-radius: 100%;
          display:block;
        }
      }
      .action{
        flex:1;
      }
    }
  }
  .addfilebtn{
    position: absolute;
    left:0;
    cursor: pointer;
  }
</style>